<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="120px">
            <el-form-item label="描述" prop="description">
              <el-input v-model="queryParams.description" clearable placeholder="请输入描述" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="queryParams.sort" clearable placeholder="请输入排序" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
            <!--              <el-input v-model="queryParams.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="标签编码" prop="tagCode">
              <el-input v-model="queryParams.tagCode" clearable placeholder="请输入标签编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="绑定目标ID" prop="bindTargetId">-->
            <!--              <el-input v-model="queryParams.bindTargetId" placeholder="请输入绑定目标ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="最后读取时间" prop="lastReadTime">
              <el-date-picker v-model="queryParams.lastReadTime" clearable placeholder="请选择最后读取时间" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <!--            <el-form-item label="最后读取的读写器ID" prop="lastReadReaderId">-->
            <!--              <el-input v-model="queryParams.lastReadReaderId" placeholder="请输入最后读取的读写器ID" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidTag:add']" icon="Plus" plain type="primary"
              @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidTag:edit']" :disabled="single" icon="Edit" plain type="success"
              @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidTag:remove']" :disabled="multiple" icon="Delete" plain type="danger"
              @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:rfidTag:export']" icon="Download" plain type="warning"
              @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="rfidTagList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <!-- <el-table-column v-if="true" align="center" label="主键ID" prop="id" /> -->
        <el-table-column align="center" label="状态" prop="status">
          <template #default="scope">
            <span v-if="scope.row.status == 0">禁用</span>
            <span v-if="scope.row.status == 1">启用</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description" />
        <el-table-column align="center" label="排序" prop="sort" />
        <!--        <el-table-column label="是否删除：0-未删除，1-已删除" align="center" prop="isDeleted" />-->
        <el-table-column align="center" label="标签编码" prop="tagCode" />
        <el-table-column align="center" label="标签类型" prop="tagType" />
        <el-table-column align="center" label="绑定状态" prop="bindStatus" >
        <template #default="scope">
            <span v-if="scope.row.bindStatus == 0">未绑定</span>
            <span v-if="scope.row.bindStatus == 1">已绑定</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="绑定目标ID" prop="bindTargetId" />
        <el-table-column align="center" label="绑定目标类型" prop="bindTargetType" />
        <el-table-column align="center" label="最后读取时间" prop="lastReadTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastReadTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后读取的读写器ID" prop="lastReadReaderId" />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['painting:rfidTag:edit']" icon="Edit" link type="primary"
                @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['painting:rfidTag:remove']" icon="Delete" link type="primary"
                @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改RFID标签管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="800px">
      <el-table v-loading="tagListLoading" :data="onlineTagList" highlight-current-row @row-click="handleTagSelect">
        <el-table-column align="center" label="标签编码" prop="epc" />
        <el-table-column align="center" label="读写器ID" prop="readerCode" />
        <el-table-column align="center" label="最后读取时间" prop="scanTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.scanTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <el-form ref="rfidTagFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <!--        <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
        <!--          <el-input v-model="form.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" />-->
        <!--        </el-form-item>-->
        <!--  标签类型      -->
        <el-form-item label="标签类型" prop="tagType">
          <el-input v-model="form.tagType" placeholder="请输入标签类型" />
        </el-form-item>
        <el-form-item label="标签编码" prop="tagCode">
          <el-input v-model="form.tagCode" placeholder="请输入标签编码" />
        </el-form-item>
        <!--  是否启用      -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="绑定目标ID" prop="bindTargetId">-->
        <!--          <el-input v-model="form.bindTargetId" placeholder="请输入绑定目标ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后读取时间" prop="lastReadTime">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.lastReadTime"-->
        <!--            type="datetime"-->
        <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--            placeholder="请选择最后读取时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后读取的读写器ID" prop="lastReadReaderId">-->
        <!--          <el-input v-model="form.lastReadReaderId" placeholder="请输入最后读取的读写器ID" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="RfidTag" setup>
import {addRfidTag, delRfidTag, getRfidTag, listRfidTag, updateRfidTag} from '@/api/painting/rfidTag';
import {RfidTagForm, RfidTagQuery, RfidTagVO} from '@/api/painting/rfidTag/types';
import {getOnlineTagList} from '@/api/painting/reader';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const rfidTagList = ref<RfidTagVO[]>([]);
const onlineTagList = ref<any[]>([]);
const tagListLoading = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const timer = ref<number>();

const queryFormRef = ref<ElFormInstance>();
const rfidTagFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RfidTagForm = {
  id: undefined,
  status: undefined,
  description: undefined,
  sort: undefined,
  isDeleted: undefined,
  tagCode: undefined,
  tagType: undefined,
  bindStatus: undefined,
  bindTargetId: undefined,
  bindTargetType: undefined,
  lastReadTime: undefined,
  lastReadReaderId: undefined
}
const data = reactive<PageData<RfidTagForm, RfidTagQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    description: undefined,
    sort: undefined,
    isDeleted: undefined,
    tagCode: undefined,
    tagType: undefined,
    bindStatus: undefined,
    bindTargetId: undefined,
    bindTargetType: undefined,
    lastReadTime: undefined,
    lastReadReaderId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0-禁用，1-启用不能为空", trigger: "change" }
    ],
    isDeleted: [
      { required: true, message: "是否删除：0-未删除，1-已删除不能为空", trigger: "blur" }
    ],
    tagCode: [
      { required: true, message: "标签编码不能为空", trigger: "blur" }
    ],
    tagType: [
      { required: true, message: "标签类型不能为空", trigger: "change" }
    ],
    bindStatus: [
      { required: true, message: "绑定状态：0-未绑定，1-已绑定不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询RFID标签管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRfidTag(queryParams.value);
  rfidTagList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 获取在线标签列表 */
const getOnlineTags = async () => {
  tagListLoading.value = true;
  try {
    const res = await getOnlineTagList();
    onlineTagList.value = res.data;
  } finally {
    tagListLoading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  // 清除定时器
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = undefined;
  }
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  rfidTagFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RfidTagVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 选择标签 */
const handleTagSelect = (row: any) => {
  form.value.tagCode = row.epc;
}

/** 启动定时刷新 */
const startTimer = () => {
  // 先清除可能存在的定时器
  if (timer.value) {
    clearInterval(timer.value);
  }
  // 设置新的定时器，每5秒刷新一次
  timer.value = window.setInterval(() => {
    getOnlineTags();
  }, 5000);
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加RFID标签管理";
  getOnlineTags();
  startTimer();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RfidTagVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRfidTag(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改RFID标签管理";
  getOnlineTags();
  startTimer();
}

/** 提交按钮 */
const submitForm = () => {
  rfidTagFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRfidTag(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addRfidTag(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RfidTagVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除RFID标签管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delRfidTag(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('painting/rfidTag/export', {
    ...queryParams.value
  }, `rfidTag_${new Date().getTime()}.xlsx`)
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = undefined;
  }
});

onMounted(() => {
  getList();
});
</script>
